package net.xinqushi.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author xjie 2019/7/17 16:25
 *  So why we use new mode Selector on non-blocking io instread of traditional mode ?
 *  使用AIO时，总是需要判断是否可读，可写 。Selector实现了判断是否读、写、连接就绪。
 */
public class SelectorClient {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();//selectable channel need a selector
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);//non-Blocking
        socketChannel.connect(new InetSocketAddress("localhost", 5555));
        while(true) {
            int readyChannels = selector.select();//block util selector event is ready
            if(readyChannels == 0) continue;//  0个就绪通道返回
            Set selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while(keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()) {
                    // a connection was accepted by a ServerSocketChannel.
                    System.out.println("a connection was accepted by a ServerSocketChannel.");
                } else if (key.isConnectable()) {
                    // a connection was established with a remote server.
                    System.out.println("a connection was established with a remote server.");
                } else if (key.isReadable()) {
                    // a channel is ready for reading
                    System.out.println(" a channel is ready for reading");
                } else if (key.isWritable()) {
                    System.out.println("a channel is ready for writing");
                    // a channel is ready for writing
                }
                keyIterator.remove();
            }
        }

    }
}
